package com.framework.web.sys.controller;


import com.framework.core.annotation.SystemControllerLog;
import com.framework.core.constant.Globals;
import com.framework.core.domain.AjaxJson;
import com.framework.core.easyui.domain.DataGridModel;
import com.framework.core.easyui.util.PageUtil;
import com.framework.core.util.MyBeanUtils;
import com.framework.core.util.POIUtil;
import com.framework.core.util.StringUtil;
import com.framework.web.common.mappings.SysUrlMappings;
import com.framework.web.sys.domain.Organization;
import com.framework.web.sys.domain.Role;
import com.framework.web.sys.service.OrganizationService;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * 资源信息管理——控制层
 *
 * @author fusf
 */
@Controller
public class OrganzationController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    /**
     * Spring注入资源信息模块service
     */
    @Autowired
    private OrganizationService organizationService;


    /**
     * 获取角色信息列表
     *
     * @param dgm
     * @param organization
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_LIST, method = RequestMethod.POST)
    @ResponseBody
    public Map<String, Object> list(DataGridModel dgm, Organization organization, HttpServletRequest request) throws Exception {
        PageRequest pr = DataGridModel.getPageRequest(dgm);
        return PageUtil.getPageMap(organizationService.getPageList(organization, pr));
    }

    /**
     * 资源信息模块添加、修改页面
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_TOSAVEANDUPDATE, method = RequestMethod.GET)
    public ModelAndView toSaveAndUpdate(@PathVariable("id") String id, @PathVariable("parentId") String parentId)
            throws Exception {
        // 进入资源信息模块添加或修改页面
        ModelAndView modelAndView = new ModelAndView(SysUrlMappings.V_SYS_ORGANIZATION_TOSAVEUPDATE);
        Organization organization = new Organization();
        if (StringUtils.isNotEmpty(id) && !"0".equals(id)) {
            organization = organizationService.findById(id);
        } else {
            // 初始化默认状态
            organization.setStatus(Globals.STATUS_YES);
            if (StringUtils.isNotEmpty(parentId) && !"0".equals(parentId)) {
                organization.setParentId(parentId);//父类Id
            }
        }
        modelAndView.addObject("organization", organization);
        return modelAndView;
    }


    /**
     * 添加或修改组资源信息构实体
     *
     * @param organization 资源信息实体
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_SAVEANDUPDATE, method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson saveAndUpdate(HttpServletRequest request, HttpServletResponse response, Organization organization) throws Exception {
        AjaxJson j = new AjaxJson();
        if (StringUtils.isNotEmpty(organization.getId())) {//更新
            if (organization.getId().equals(organization.getParentId())) {
                j.setSuccess(false);
                j.setMsg("上级机构不能选择自身");
                return j;
            }
            Organization r = organizationService.findById(organization.getId());
            MyBeanUtils.copyBeanNotNull2Bean(organization, r);
            organization = r;
        } else {
            organization.setLevel(organizationService.getMaxLevel(organization.getParentId()));
        }
        organization.setStatus(Globals.USER_NORMAL);
        organizationService.save(organization);
        j.setMsg("机构信息保存成功");
        return j;
    }

    /**
     * 根据id字符串删除指定资源信息数据
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_DELETE, method = RequestMethod.POST)
    @ResponseBody
    public AjaxJson delete(String id) throws Exception {
        AjaxJson j = new AjaxJson();
        organizationService.delete(id);
        j.setMsg("删除成功");
        return j;
    }

    /**
     * 获取组织机构树json数据
     *
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_COMMONTREEMORE)
    @ResponseBody
    public Object commonTreeMore(HttpServletRequest request, HttpServletResponse response) throws Exception {
        List<Organization> organizationList = organizationService.findAll();
        return organizationService.findTreeOrganization(organizationList);
    }

    /**
     * 根据ID查询名称
     *
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_GETORGNAMEBYID)
    @ResponseBody
    public AjaxJson getOrgNameById(String id) throws Exception {
        AjaxJson j = new AjaxJson();
        Organization organization = organizationService.findById(id);
        j.setObj(organization.getOrgName());
        return j;
    }


    /**
     * 通过excel导入组织机构信息
     *
     * @param organFile
     * @param request
     * @return
     */
    @RequestMapping(value = SysUrlMappings.SYS_ORGANIZATION_IMPORT_EXCEL, method = RequestMethod.POST, produces = "text/html;charset=UTF-8")
    @ResponseBody
    //@SystemControllerLog(description = "导入组织机构信息")
    public void importExcel(@RequestParam(value = "organFile", required = true) MultipartFile organFile,
                            HttpServletRequest request, HttpServletResponse response) throws Exception {
        String errorMessage = "";
        int count = 0;
        InputStream inp = organFile.getInputStream();
        Workbook wb = new HSSFWorkbook(inp);
        Sheet sheet = wb.getSheetAt(0);
        for (int i = 1; i <= sheet.getLastRowNum(); i++) {
            String result = "";
            Row row = sheet.getRow(i);
            if (row == null) {
                break;
            }
            String orgName = POIUtil.getValue(row.getCell(0));//机构名称
            if (StringUtil.isEmpty(orgName)) {
                result += "第" + i + "行 机构名称为空！\t";
            }

            String parentName = POIUtil.getValue(row.getCell(1));
            String parentId = "";
            List<Organization> organizationList = organizationService.findByOrgName(parentName);
            if (organizationList != null && organizationList.size() == 1) {
                parentId = organizationList.get(0).getId();
            } else if (organizationList != null && organizationList.size() > 1) {
                result += "第" + i + "行 上级机构名称查询有多个数据，无法匹配！\t";
            }
            if ("".equals(result)) {
                try {
                    Organization organization = new Organization();
                    organization.setOrgName(orgName);//机构名称
                    organization.setContractPerson(POIUtil.getValue(row.getCell(2)));//联系人
                    organization.setAddress(POIUtil.getValue(row.getCell(3)));//联系地址
                    organization.setTel(POIUtil.getValue(row.getCell(4)));//联系电话
                    organization.setRemark(POIUtil.getValue(row.getCell(5)));//备注
                    organization.setStatus(Globals.USER_NORMAL);//正常
                    organization.setParentId(parentId);//父类Id
                    organization.setLevel(organizationService.getMaxLevel(organization.getParentId()));//level
                    organizationService.save(organization);
                    count++;
                } catch (Exception e) {
                    e.printStackTrace();
                    logger.error(e.getMessage());
                }
            } else {
                errorMessage += result;
            }

        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("fileId", organFile.getName());
        jsonObject.put("value", errorMessage);
        jsonObject.put("count", count);
        response.setContentType("text/html;charset=UTF-8");
        response.getWriter().println(jsonObject.toString());
    }


}